package com.wyd.jwpkglxt_ssm.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.wyd.jwpkglxt_ssm.entity.Role;
import com.wyd.jwpkglxt_ssm.entity.User;
import com.wyd.jwpkglxt_ssm.entity.UserRole;
import com.wyd.jwpkglxt_ssm.service.UserRoleService;
import com.wyd.jwpkglxt_ssm.service.UserService;
import com.wyd.jwpkglxt_ssm.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.*;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2021-07-22 16:09:45
 */
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @PostMapping("login")
    public ResultUtil login(@RequestParam(required = false) String username, @RequestParam(required = false) String password,
                            @RequestParam(value = "verifycode",required = false)String verifyCode, HttpServletRequest request){
        HttpSession session = request.getSession();
        String code = session.getAttribute("code").toString();
        if(code.equals(verifyCode)){
            if(username!=null&&password!=null){
                User loginUser = this.userService.login(username,password);
                if(!Objects.isNull(loginUser)){
                    if(loginUser.getStatus()==0){
                        return ResultUtil.error(ResultCode.USERNAME_STATUS_OFF);
                    }
                    Map<String, String> payload = new HashMap<>();
                    payload.put("username",loginUser.getUsername());
                    payload.put("userId",loginUser.getId().toString());
                    payload.put("realName",loginUser.getRealName());
                    payload.put("roleId",loginUser.getRole().getId().toString());
                    String token = JWTUtil.getToken(payload);
                    session.setAttribute("token", token);
                    return ResultUtil.ok().data("user",loginUser).data("token",token);
                }else{
                    //登录用户名或密码错误!
                    return ResultUtil.error(ResultCode.USERNAME_OR_PASSWORD_ERROR);
                }
            }else{
                //登录用户名或密码为空!请检查后重新登录
                return ResultUtil.error(ResultCode.USERNAME_OR_PASSWORD_EMPTY);
            }
        }else{
            return ResultUtil.error(ResultCode.VERIFYCODE_ERROR);
        }
    }

    @PostMapping("user")
    public ResultUtil insertUser(@RequestBody User user) {
        if(!Objects.isNull(user)){
            User insertUser = this.userService.insert(user);
            if(!Objects.isNull(insertUser)){
                return ResultUtil.ok();
            }
        }
        return ResultUtil.error(ResultCode.UNKNOWN_ERROR);
    }


    @GetMapping("user/page")
    public ResultUtil getAllUserWithRoleByPage(Integer pageNum, Integer pageSize,
                                               @RequestParam(required = false) String username,@RequestParam(required = false) String realName,
                                               @RequestParam(required = false) Integer status,@RequestParam(required = false) Integer roleId,
                                               HttpServletRequest request) {
        String token = request.getHeader("authorization");
        User user = new User().setUsername(username).setRealName(realName).setStatus(status).setRole(new Role().setId(roleId));
        return ResultUtil.ok().data("pageInfo",this.userService.selectAllWithRoleByPage(pageNum,pageSize,user));
    }

    @PutMapping("user")
    public ResultUtil updateUser(@RequestBody User user){
        if(!Objects.isNull(user)){
            User updateUser = this.userService.update(user);
            if(!Objects.isNull(updateUser)){
                //如果角色不为空则更新用户角色表
                return ResultUtil.ok();
            }
        }
        return ResultUtil.error(ResultCode.UNKNOWN_ERROR);
    }

    @GetMapping("user/info")
    public ResultUtil getUserInfoByToken(HttpServletRequest request){
        String token = request.getHeader("authorization");
        DecodedJWT verify = JWTUtil.verify(token);
        return ResultUtil.ok().data("userId",verify.getClaim("userId").asString()).data("username",verify.getClaim("username").asString())
                .data("realName",verify.getClaim("realName").asString()).data("roleId",verify.getClaim("roleId").asString());
    }

    @DeleteMapping("user/{userId}")
    public ResultUtil deleteUserById(@PathVariable("userId")String ids){
        System.out.println(ids);
        if(ids.contains("-")){
            String[] idsplit = ids.split("-");
            List<Integer> userIds = new ArrayList<>();
            for(String s : idsplit){
                userIds.add(Integer.parseInt(s));
            }
            boolean delUsers = this.userService.deleteUserBatch(userIds);
            if(delUsers){
                List<UserRole> userRoles = this.userRoleService.queryAllByUserIdsBatch(userIds);
                List<Integer> userRoleIds = new ArrayList<>();
                for(UserRole userRole : userRoles){
                    userRoleIds.add(userRole.getId());
                }
                boolean delUserRoles = this.userRoleService.deleteUserRoleBatch(userRoleIds);
                if(delUserRoles){
                    return ResultUtil.ok();
                }
            }
        }else if(!"".equals(ids)){
            Integer id = Integer.parseInt(ids);
            boolean delUser = this.userService.deleteById(id);
                if(delUser){
                    UserRole userRole = this.userRoleService.queryAll(new UserRole().setUserId(id)).get(0);
                    boolean delUserRole = this.userRoleService.deleteById(userRole.getId());
                    if(delUserRole){
                        return ResultUtil.ok();
                    }
                }
        }

        return ResultUtil.error(ResultCode.UNKNOWN_ERROR);
    }

    @PatchMapping("user/status")
    public ResultUtil UpdateUserStatusBatch(@RequestBody String ids){
        //去掉队头队尾双引号
        String idsr = ids.replace("\"","");
        if(!"".equals(idsr)){
            if(idsr.contains(".on")){
                String[] split_ids = idsr.split("-");
                split_ids[split_ids.length - 1] = split_ids[split_ids.length - 1].split(".on")[0];
                List<Integer> userIds = new ArrayList<>();
                for(String id : split_ids){
                    userIds.add(Integer.parseInt(id));
                }
                int i = this.userService.updateStatusBatch(userIds, 1);
                if(i > 0){
                    return ResultUtil.ok();
                }else{
                    return ResultUtil.error(ResultCode.UNKNOWN_ERROR);
                }
            }else if(idsr.contains(".off")){
                String[] split_ids = idsr.split("-");
                split_ids[split_ids.length - 1] = split_ids[split_ids.length - 1].split(".off")[0];
                List<Integer> userIds = new ArrayList<>();
                for(String id : split_ids){
                    userIds.add(Integer.parseInt(id));
                }
                int i = this.userService.updateStatusBatch(userIds, 0);
                if(i > 0){
                    return ResultUtil.ok();
                }else{
                    return ResultUtil.error(ResultCode.UNKNOWN_ERROR);
                }
            }
        }
        return ResultUtil.error(ResultCode.UNKNOWN_ERROR);
    }

    @PostMapping("image")
    public ResultUtil uploadImage(@RequestParam("file") MultipartFile multipartFile,HttpServletRequest request) throws IOException {
        //String url = request.getSession().getServletContext().getRealPath("/upload");


        //String imagePath = UploadUtil.upload(multipartFile,url);
        //if (imagePath!=null){
        //    return ResultUtil.ok().data("src",imagePath);
        //}

        return ResultUtil.error(ResultCode.UNKNOWN_ERROR);

    }

    @PatchMapping("user/pw")
    public ResultUtil updateUserPassword(Integer userId,String originPassword,String newPassword){
        if(userId!=null&&originPassword!=null&&newPassword!=null){
            User user = this.userService.queryById(userId);
            if(!Objects.isNull(user)){
                String beforePassword = user.getPassword();
                String salt = user.getSalt();
                String afterPassword = MD5Util.MD5EncodeUtf8(originPassword+salt);
                if(beforePassword.equals(afterPassword)){
                    User update = this.userService.update(new User().setId(userId).setPassword(newPassword));
                    if(!Objects.isNull(update)){
                        return ResultUtil.ok();
                    }
                }else{
                    return ResultUtil.error(ResultCode.ORIGIN_PASSWORD_ERROR);
                }
            }
        }
        return ResultUtil.error(ResultCode.UNKNOWN_ERROR);

    }
}